﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Debug = UnityEngine.Debug;

namespace CxExtension
{
	public class PathGroup
	{
		private HashSet<string> mPaths = new HashSet<string>();                      //

		public void AddPath(string path)
		{
			mPaths.Add(path);
		}

		public void AddPath(IEnumerable<string> emnu)
		{
			foreach (var it in emnu)
			{
				AddPath(it);
			}
		}

		/// <summary>
		/// 尝试定位file是否存在于路劲中
		/// </summary>
		/// <param name="file"></param>
		/// <param name="path"></param>
		/// <returns></returns>
		public bool TryLocal(string file, out string path)
		{
			foreach (var it in mPaths)
			{
				var newpath = PathUtil.Combine(it, file);
				if (File.Exists(newpath))
				{
					path = newpath;
					return true;
				}
			}
			
			var bld = new StringBuilder();
			bld.AppendLine(string.Format("not find file:{0},in:", file));
			foreach (var it in mPaths)
			{
				bld.AppendLine(PathUtil.Combine(it, file));
			}
			Debug.LogError(bld.ToString());

			path = string.Empty;
			return false;
		}

		public bool ExistInPaths(string file)
		{
			string path;
			return TryLocal(file, out path);
		}

		public static PathGroup Parse(string str)
		{
			var strs = str.Split(';');
			var ins = new PathGroup();
			foreach (var it in strs)
			{
				ins.AddPath(it);
			}

			return ins;
		}

		public override string ToString()
		{
			var build = new StringBuilder();
			foreach (var it in mPaths)
			{
				build.AppendFormat("{0};", it);
			}

			build.Remove(build.Length - 1, 1);
			return base.ToString();
		}

		public static implicit operator PathGroup(List<string> a)
		{
			var ins = new PathGroup();
			ins.AddPath(a);
			return ins;
		}
	}
}
